package com.school.sports.filter;
import com.school.sports.util.CurrentHolder;
import com.school.sports.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@Component
@WebFilter(urlPatterns = "/*")  // 拦截所有请求
public class TokenFilter implements Filter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;       //请求数据
        HttpServletResponse response = (HttpServletResponse) servletResponse;   //响应数据

        //1.获取到请求路径
        String requestURI = request.getRequestURI();    // employees/login

        //2.判断是否是登录请求，如果路径中包含/login，说明是登录操作，放行
        if(requestURI.contains("/login")){
            log.info("登录操作...放行");
            filterChain.doFilter(request,response); //放行
            return;
        }

        //3.获取请求头中的token
        String token = request.getHeader("token");

        //4.判断token是否存在，如果不存在，说明用户没有登录，返回错误信息(响应401状态码)
        if(token == null || token.isEmpty()){
            log.info("令牌为空,响应401");
            response.setStatus(401);

            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未提供访问令牌，请先登录\",\"data\":null}");
            return;
        }

        //5.如果token存在，校验令牌，如果校验失败->返回错误信息(响应401状态码)
        try {
            // 验证token格式
            String username = jwtUtil.getUsernameFromToken(token);
            if (username != null && jwtUtil.validateToken(token, username)) {
                Long userId = jwtUtil.getUserIdFromToken(token);
                CurrentHolder.setCurrentId(userId);  //存入当前登录用户ID
                log.info("当前登录用户ID为：{},将其存入ThreadLocal", userId);
            } else {
                throw new Exception("Token验证失败");
            }
        } catch (Exception e) {
            log.info("令牌校验失败，响应401");
            response.setStatus(401);

            // 添加错误信息返回
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"code\":401,\"message\":\"令牌无效或已过期，请重新登录\",\"data\":null}");
            return;
        }

        //6.如果校验成功，说明用户登录成功，放行
        log.info("令牌校验成功，放行");
        filterChain.doFilter(request,response);

        //7.删除ThreadLocal中的数据
        CurrentHolder.remove();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化方法，可以为空
    }

    @Override
    public void destroy() {
        // 销毁方法，可以为空
    }
}

